package com.gzxx.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.gzxx.constant.ServiceCodeStatus;
import com.gzxx.constant.SystemConstant;
import com.gzxx.domain.base.BaseVo;
import com.gzxx.domain.base.RequestPage;
import com.gzxx.domain.bo.SysRoleBO;
import com.gzxx.domain.po.SysRole;
import com.gzxx.domain.vo.SysRoleVo;
import com.gzxx.domain.vo.SysUserRoleVo;
import com.gzxx.exception.ServiceException;
import com.gzxx.mapper.SysRoleMapper;
import com.gzxx.mapper.SysRoleMenuMapper;
import com.gzxx.mapper.SysUserRoleMapper;
import com.gzxx.service.SysMenuService;
import com.gzxx.service.SysRoleService;
import com.gzxx.util.ServerResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author MAX
 * @date 2020/7/24 9:38 上午
 */

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Transactional(readOnly = true, rollbackFor = Exception.class, timeout = 5)
public class SysRoleServiceImpl implements SysRoleService {

    private final SysRoleMapper sysRoleMapper;
    private final SysRoleMenuMapper sysRoleMenuMapper;
    private final SysUserRoleMapper sysUserRoleMapper;

    private final SysMenuService sysMenuService;

    @Override
    public SysRoleVo getByUserId(Long userId) {
        return sysRoleMapper.getByUserId(userId);
    }

    /**
     * 根据查询条件获取角色列表
     */
    @Override
    public IPage<SysRoleVo> getRoles(SysRoleBO sysRoleBO) {
        try {
            Map<?, ?> queryParams = sysRoleBO.queryParams();
            RequestPage requestPage = sysRoleBO.getPage();
            Page<SysRoleVo> page = new Page<>(requestPage.getPage(), requestPage.getPageSize());
            return sysRoleMapper.queryRoles(page, queryParams);
        } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            throw new ServiceException("class:SysRoleServiceImpl method:getRoles exception", e);
        }
    }

    /**
     * 详情
     */
    @Override
    public SysRoleVo getDetail(Long id) {
        SysRoleVo sysRoleVo = sysRoleMapper.singleDetail(id);
        // 查询角色所有菜单
        List<Long> menuList = sysRoleMenuMapper.queryByRoleId(id);
        // 查询所有父级节点
        List<Long> parentList = sysMenuService.getParentAll();
        // 排除所有父级节点 只返回子节点
        menuList = menuList.stream().filter(menuId -> !parentList.contains(menuId)).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(menuList)) {
            sysRoleVo.setMenuIds(menuList);
        }
        return sysRoleVo;
    }

    /**
     * 新增
     */
    @Transactional(rollbackFor = Exception.class, timeout = 5)
    @Override
    public boolean add(SysRoleBO sysRoleBO) {
        SysRole role = sysRoleBO.create();
        int roleNum = sysRoleMapper.insert(role);
        int roleMenuNum = 0;
        // 角色菜单关系
        if (roleNum > 0) {
            roleMenuNum = sysRoleMenuMapper.insertBach(sysRoleBO.createRoleMenu(role.getId()));
        }
        return roleNum > 0 && roleMenuNum > 0;
    }

    /**
     * 更新
     */
    @Transactional(rollbackFor = Exception.class, timeout = 5)
    @Override
    public ServerResponse update(SysRoleBO sysRoleBO) {
        // 管理员
        if (sysRoleBO.getId().equals(SystemConstant.ADMIN_ID)) {
            return ServerResponse.error("管理员禁止修改");
        }
        boolean result = false;
        SysRole role = sysRoleBO.edit();
        if (!StringUtils.isEmpty(role.getRoleName())) {
            int roleNum = sysRoleMapper.updateById(role);
            result = roleNum > 0;
        }
        if (!ObjectUtils.isEmpty(sysRoleBO.getMenuIds())) {
            // 先删除
            sysRoleMenuMapper.deleteByRoleId(role.getId());
            int roleMenuNum = sysRoleMenuMapper.insertBach(sysRoleBO.createRoleMenu(role.getId()));
            result = roleMenuNum > 0;
        }
        return result ? ServerResponse.success(ServiceCodeStatus.SUCCESS) : ServerResponse.error();
    }

    /**
     * 变更角色状态
     */
    @Transactional(rollbackFor = Exception.class, timeout = 5)
    @Override
    public ServerResponse changeStatus(SysRoleBO sysRoleBO) {
        // 管理员
        if (sysRoleBO.getId().equals(SystemConstant.ADMIN_ID)) {
            return ServerResponse.error("管理员禁止修改");
        }
        int num = sysRoleMapper.updateById(sysRoleBO.changeStatus());
        return num > 0 ? ServerResponse.success(ServiceCodeStatus.SUCCESS) : ServerResponse.error();
    }

    /**
     * 删除 批量
     */
    @Transactional(rollbackFor = Exception.class, timeout = 5)
    @Override
    public ServerResponse delete(List<Long> ids) {
        List<Long> userIds = sysUserRoleMapper.queryBachByRoleIds(ids);
        if (!ObjectUtils.isEmpty(userIds)) {
            return ServerResponse.error("存在关联用户，禁止删除");
        }
        int num = sysRoleMapper.deleteBatchIds(ids);
        if (num > 0) {
            // 删除角色用户关系
            sysRoleMenuMapper.deleteBachByRoleIds(ids);
        }
        return num > 0 ? ServerResponse.success(ServiceCodeStatus.SUCCESS) : ServerResponse.error();
    }

    @Override
    public List<Long> queryAllMenuId(Long userId) {
        return sysRoleMapper.queryAllMenuId(userId);
    }

    /**
     * 获取所有角色
     */
    @Override
    public List<BaseVo> getAll() {
        return sysRoleMapper.queryAll();
    }

    /**
     * 获取角色关联用户 树形
     */
    @Override
    public List<BaseVo> tree() {
        List<BaseVo> roles = Lists.newArrayList();
        List<SysUserRoleVo> userRoleVos = sysRoleMapper.queryAllRoleUser();
        if (ObjectUtils.isEmpty(userRoleVos)) {
            return null;
        }
        Map<Long, List<SysUserRoleVo>> map = userRoleVos.stream().collect(Collectors.groupingBy(SysUserRoleVo::getRoleId));
        map.forEach((k, v) -> {
            List<SysUserRoleVo> sysUserRoleVos = v;
            BaseVo role = new BaseVo();
            roles.add(role);
            role.setLabel(sysUserRoleVos.get(0).getRoleName());
            // TODO 此处修改  解决roleId与userId冲突问题
            //role.setValue(sysUserRoleVos.get(0).getRoleId());
            role.setStatus(sysUserRoleVos.get(0).getRoleStatus());
            List<BaseVo> users = Lists.newArrayList();
            role.setChildren(users);
            for (SysUserRoleVo userRoleVo : sysUserRoleVos) {
                BaseVo user = new BaseVo();
                user.setParentId(userRoleVo.getRoleId());
                user.setLabel(userRoleVo.getUserName());
                user.setValue(userRoleVo.getUserId());
                user.setStatus(userRoleVo.getUserStatus());
                if (SystemConstant.NOEFFECTIVE.equals(userRoleVo.getRoleStatus())) {
                    user.setStatus(SystemConstant.NOEFFECTIVE);
                }
                users.add(user);
            }
        });
        return roles;
    }
}
